package server

import (
	"context"
	"errors"
	"house-src/basic/config"
	__ "house-src/basic/proto"
	"house-src/handler/models"
	"house-src/pkg"
)

// 客户注册
func (s *Server) CustomerLogin(_ context.Context, in *__.CustomerLoginReq) (*__.CustomerLoginResp, error) {
	var err error

	var customer models.Customer
	if err = customer.GetCustomerInfo(in.Mobile); err != nil {
		return nil, errors.New("客户查询失败")
	}

	if customer.ID == 0 {

		//短信验证
		code := config.Rdb.Get(config.Ctx, "sendSms"+in.Mobile).Val()
		if code != in.SmsCode {
			return nil, errors.New("短信验证码错误")
		}

		customer = models.Customer{
			Mobile:   in.Mobile,
			Password: pkg.Md5(in.Password),
			UType:    1,
			Status:   1, //正常
		}
		if err = customer.AddCustomer(); err != nil {
			return nil, errors.New("客户注册失败")
		}

	} else {
		if customer.Password != pkg.Md5(in.Password) {
			return nil, errors.New("用户已存在")
		}
	}

	return &__.CustomerLoginResp{
		CustomerId: int64(customer.ID),
	}, nil
}
